package com.cm.etax.tianjin;

import com.cm.etax.BaseEtax;
import com.cm.etax.BaseFunction;
import com.cm.etax.FunctionResult;
import com.cm.etax.exceptions.EtaxException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;

import java.util.Objects;

/**
 * 企业切换管理方法
 *
 * @author LWang 2023.01.29
 * @since 1.0.0
 */
@Slf4j
public class SwitchTaxpayerFunction extends BaseFunction {
    public SwitchTaxpayerFunction(BaseEtax etax) {
        super(etax);
    }

    /**
     * 切换企业
     *
     * @param taxFileNo 税号
     * @return 切换结果
     */
    public FunctionResult<Object> switchTaxpayer(String taxFileNo) {
        // 1. 进入“我的信息” - “企业账户中心” 功能
        {
            var functionResult = etax().function(MenuFunction.class).choiceMainMenu("我的信息", "企业账户中心（代理账号中心）");
            if (!functionResult.success()) {
                return new FunctionResult<>(false, "切换企业失败，" + functionResult.message(), null);
            }
        }
        // 2. 进入“身份切换” - “企业办税” 功能
        {
            var functionResult = etax().function(MenuFunction.class).choiceAccountCenterMenu("身份切换", "企业办税");
            if (!functionResult.success()) {
                return new FunctionResult<>(false, "切换企业失败，" + functionResult.message(), null);
            }
        }
        try {
            rpa().findElementWithInnerText("企业办税", By.cssSelector("div.s_Breadcrumb"), WAIT_TIME);
            // 3. 切换到“企业企业切换”标签
            rpa().click(By.id("tab-2"), WAIT_TIME);
            // 4. 输入要切换到的税号
            rpa().sendKey(By.cssSelector("input.el-input__inner[placeholder=\"请输入统一社会信用代码\"]"), taxFileNo, true, WAIT_TIME);
            // 5. 查询，并等待结果返回
            rpa().newHar();
            rpa().findElementWithInnerText("查询", By.cssSelector("div.other-enterprise div.search-form button.el-button span"), WAIT_TIME).click();
            rpa().listen("idm/internal/relation/selectRelationList");
            // 6. 在结果列表中查找税号是否存在
            var rows = rpa().findElements(By.cssSelector("div.other-enterprise table.el-table__body tr.el-table__row"), WAIT_TIME);
            WebElement choiceButton = null;
            for (var row : rows) {
                var cells = row.findElements(By.cssSelector("td .cell"));
                for (var cell : cells) {
                    if (rpa().textEquals(cell, taxFileNo)) {
                        choiceButton = row.findElement(By.cssSelector(".el-button.el-button--text.el-button--small"));
                    }
                }
                if (!Objects.isNull(choiceButton)) {
                    break;
                }
            }
            // 7. 执行切换功能
            if (Objects.isNull(choiceButton)) {
                throw new EtaxException("当前用户未关联" + taxFileNo);
            }
            rpa().newHar();
            choiceButton.click();
            rpa().listen("idm/internal/relation/selectRelationList");
            rpa().sleep(SLEEP_TIME);
            // 判断 URL 是否是税务局首页，如果不是，查找角色选择对话框
            if (!StringUtils.contains(rpa().url(), config().getHomeUri())) {
                var dialog = rpa().findElement(By.cssSelector(".el-dialog.el-dialog--center"), WAIT_TIME);
                var header = dialog.findElement(By.cssSelector(".el-dialog__title"));
                var headerText = "身份类型选择";
                if (rpa().textEquals(header, headerText)) {
                    var choice = false;
                    for (var role : etax().getRoles()) {
                        try {
                            rpa().click(rpa().findElementWithInnerText(role, By.cssSelector(".el-radio .el-radio__label"), WAIT_TIME));
                            choice = true;
                            break;
                        } catch (NoSuchElementException ignore) {
                        }
                    }
                    if (!choice) {
                        throw new EtaxException("无法识别的角色！");
                    }
                    dialog.findElement(By.cssSelector("button.el-button.el-button--primary")).click();
                } else {
                    throw new EtaxException("出现未知的对话框信息，" + header.getText());
                }
            }
            // 8. 等待返回电子税务局首页
            rpa().waitElement(By.cssSelector("div.user span.userName span.userNameInfo"), WAIT_TIME);
            // 8.1 补充……因为电子税务局的 bug，需要清理电子税务局内部网上办税子系统的 Cookies
            try {
                rpa().removeCookies("WSBSSESSION");
            } catch (Exception ignore) {
            }
            // 9. 返回结果
            return new FunctionResult<>(true, "切换企业成功。", null);
        } catch (Exception e) {
            return handleException(e, "切换企业失败，发生未知异常！");
        }
    }
}
